package com.android.view.activity.quote;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.R;
import com.android.app.CommonType;
import com.android.app.constant.UrlConstants;
import com.android.model.entity.res.SnapListResult;
import com.android.model.info.LocalSp;
import com.android.util.Arithmetic;
import com.android.util.HqKlineDb;
import com.android.util.JsonUtil;
import com.android.util.ToastUtil;
import com.android.view.activity.base.ToolbarBaseActivity;
import com.android.view.activity.trade.TradeActivity;
import com.android.view.adapter.PopSelectListAdapter;
import com.android.view.hqview.BaseChartView;
import com.android.view.hqview.IndexModel;
import com.android.view.hqview.KLineView;
import com.android.view.hqview.MinutesView;
import com.android.view.widget.CanAddListenerScrollView;
import com.android.view.widget.CommonHeaderView;
import com.android.view.widget.pop.SelectListPop;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 行情
 * Created by TenFace on 2018/5/4.
 */

public class MarketInfoActivity extends ToolbarBaseActivity {

    @BindView(R.id.mChartLayout)
    FrameLayout mChartLayout;
    @BindView(R.id.flChartTop)
    FrameLayout flChartTop;
    @BindView(R.id.quoteInfoScrollView)
    CanAddListenerScrollView nestedScrollView;
    @BindView(R.id.tvMarketPrice)
    TextView tvMarketPrice;
    @BindView(R.id.ivMarketPrice)
    ImageView ivMarketPrice;
    @BindView(R.id.tvMarketPriceCNY)
    TextView tvMarketPriceCNY;
    @BindView(R.id.tvMarketPercent)
    TextView tvMarketPercent;
    @BindView(R.id.tvMarket24Vol)
    TextView tvMarket24Vol;
    @BindView(R.id.tvMarket24Low)
    TextView tvMarket24Low;
    @BindView(R.id.tvMarket24High)
    TextView tvMarket24High;
    @BindView(R.id.information_tv_tab_financial_reporting)
    TextView tvIndex;
    @BindView(R.id.tradeCommonHeader)
    CommonHeaderView tradeCommonHeader;
    @BindView(R.id.llStockBuy)
    LinearLayout llStockBuy;
    @BindView(R.id.llStockSell)
    LinearLayout llStockSell;
    @BindViews({R.id.information_tv_tab_news, R.id.information_tv_tab_notification, R.id.information_tv_tab_information, R.id.information_tv_tab_day})
    TextView[] informationTvs;
    @BindViews({R.id.information_tab_news_line, R.id.information_tab_notification_line, R.id.information_tab_information_line, R.id.information_tab_financial_reporting_line})
    View[] informationViewLine;
    @BindView(R.id.information_tab_index_line)
    View indexView;
    @BindViews({R.id.information_tab_news_ll_line, R.id.information_tab_notification_ll_line, R.id.information_tab_information_ll_line, R.id.information_tab_financial_reporting_ll_line})
    LinearLayout[] llLines;
    @BindView(R.id.information_ll_tab_financial_reporting)
    LinearLayout llFinancialReporting;
    String[] informationTabName = {"min", "1m", "1h", "1d"};
    private BaseChartView mBaseChartView = null;
    private String[] tabStr = new String[]{"min", "1m", "1h", "1d"};
    private String[] typeStr = new String[]{CommonType.TIME_TYPE_MIN, CommonType.TIME_TYPE_ONE_MIN, CommonType.TIME_TYPE_ONE_HOUR, CommonType.TIME_TYPE_DAY};
    private Bundle mBundle;
    private String name = "$dxy";
    private boolean isScroll;
    private HqKlineDb hqKlineDb;
    private Context context;
    private static String intentKey = "SYMBOL";
    private static String intentKey2 = "TYPE";
    private String type;
    private String title;
    int infoCurrentIndex = 0;
    int topSelectPosition = 0;
    int bottomSelectPosition = 0;
    String[] topSelectStr = {"MA", "BOLL"};
    String[] bottomSelectStr = {"VOL","MACD", "KDJ", "RSI", "ADX", "ATR"};

    public static void actionStart(Context context, String symbol, String type) {
        Intent intent = new Intent(context, MarketInfoActivity.class);
        intent.putExtra(intentKey, symbol);
        intent.putExtra(intentKey2, type);
        context.startActivity(intent);
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_quote_stock_info);
    }

    @Override
    protected void initView() {
        context = this;
        isScroll = true;

        Intent intent = getIntent();
        title = intent.getStringExtra(intentKey);
        type = intent.getStringExtra(intentKey2);
        tradeCommonHeader.setTitle(title + " / " + type);

        hqKlineDb = new HqKlineDb(context);
        hqKlineDb.setClearIndex();//首次进入则清理指标记录

        mBundle = new Bundle();
        mBundle.putString("name", name);
        mBundle.putBoolean("isScroll", isScroll);

        for (int i = 0; i < informationTvs.length; i++) {
            informationTvs[i].setText(informationTabName[i]);
            informationTvs[i].setVisibility(View.VISIBLE);
            llLines[i].setVisibility(View.VISIBLE);

//            //隐藏财报
//            if (i == informationTvs.length - 1) {
//                llFinancialReporting.setVisibility(View.GONE);
//                llLines[i].setVisibility(View.GONE);
//            }
        }

    }

    @Override
    protected void obtainData() {
        snapTimer.start();
    }

    @Override
    protected void initEvent() {

        llStockBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TradeActivity.actionStart(context, title, type);
            }
        });

        llStockSell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TradeActivity.actionStart(context, title, type);
            }
        });

        setCurrentItem(0);
        informationTvs[0].setOnClickListener(new InformationTabClick(0));
        informationTvs[1].setOnClickListener(new InformationTabClick(1));
        informationTvs[2].setOnClickListener(new InformationTabClick(2));
        informationTvs[3].setOnClickListener(new InformationTabClick(3));
        llFinancialReporting.setOnClickListener(new InformationTabClick(4));

        llFinancialReporting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llFinancialReporting.setBackgroundColor(getColor(R.color.market_index_bg));
                SelectListPop.getInstance().show(indexView, topSelectPosition, bottomSelectPosition, Arrays.asList(topSelectStr), Arrays.asList(bottomSelectStr), new PopSelectListAdapter.ItemClick() {
                    @Override
                    public void click(int position, int type) {
                        if (type == 0) {
                            topSelectPosition = position;
                            if (mBaseChartView != null) {
                                mBaseChartView.getIndexView(context).changeAdjust(IndexModel.ADJUSTTYPES[position]);
                            }
                        } else {
                            bottomSelectPosition = position;
                            mBaseChartView.getIndexView(context).changeIndex(IndexModel.INDEXTYPES[position]);
                        }
                        ToastUtil.show("Position=" + position + ",Type=" + type);
                        SelectListPop.getInstance().close();
                        llFinancialReporting.setBackgroundColor(getResourceColor(R.color.main_title_bg));
                    }

                    @Override
                    public void close() {
                        llFinancialReporting.setBackgroundColor(getResourceColor(R.color.main_title_bg));
                    }
                });
            }
        });

    }

    private class InformationTabClick implements View.OnClickListener {
        int index;

        InformationTabClick(int index) {
            this.index = index;
        }

        @Override
        public void onClick(View v) {
            initKLineView(index);

        }
    }

    /***
     * 默认选中条目
     * @param position index
     */
    private void setCurrentItem(int position) {
        initKLineView(position);

    }

    /***
     * 初始化K线或者分时线
     * @param position index
     */
    private void initKLineView(int position) {
        informationFocusState(position);

        if (mBaseChartView != null) {
            mBaseChartView.unRegister();
            mBaseChartView.destroy();
            mChartLayout.removeView(mBaseChartView);
            mBaseChartView.setActive(false);
        }
        mBundle.putString("typeLine", typeStr[position]);
        mBundle.putInt("tabIndex", position);//传入选择的TabScrollButton的position

        switch (position) {
            case 0://分时
                mBundle.putBoolean("fullScreen", false);
                mBaseChartView = new KLineView(context, flChartTop, mBundle, 0);
                mBaseChartView.setActive(true);
                break;
            case 1://1min
                mBundle.putBoolean("fullScreen", false);
                mBaseChartView = new KLineView(context, flChartTop, mBundle, 0);
                break;
            case 2://1h
                mBundle.putBoolean("fullScreen", false);
                mBaseChartView = new KLineView(context, flChartTop, mBundle, 0);
                break;
            case 3://1d
                mBundle.putBoolean("fullScreen", false);
                mBaseChartView = new KLineView(context, flChartTop, mBundle, 0);
                break;

        }

        mChartLayout.addView(mBaseChartView);
        mBaseChartView.start();
        mBaseChartView.initData();
    }

    private void informationFocusState(int position) {
        try {
            for (int i = 0; i < informationTvs.length; i++) {
                if (i == position) {
                    informationTvs[i].setTextColor(getResources().getColor(R.color.main_white));
                    informationViewLine[i].setVisibility(View.VISIBLE);
                } else {
                    informationTvs[i].setTextColor(getResources().getColor(R.color.main_button));
                    informationViewLine[i].setVisibility(View.GONE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getSnapData() {
        List<String> stringList = new ArrayList<>();
        stringList.add(title + type);

        OkGo.get(UrlConstants.HOST_HTTPS + UrlConstants.MARKET_REALTIME_SNAP)
                .addUrlParams("symbol", stringList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        SnapListResult snapListResult = JsonUtil.parseJsonToBean(s, SnapListResult.class);
                        if (snapListResult != null) {
                            double percent = Arithmetic.getPercent(snapListResult.get_$55TBTC().getData().getLast(), snapListResult.get_$55TBTC().getData().getPreviousClose());

                            if (percent > 0) {
                                ivMarketPrice.setBackgroundResource(R.mipmap.market_up);
                                tvMarketPrice.setTextColor(LocalSp.getInstance(context).getBeginColor());
                                tvMarketPercent.setTextColor(LocalSp.getInstance(context).getBeginColor());
                            } else if (percent < 0) {
                                ivMarketPrice.setBackgroundResource(R.mipmap.market_down);
                                tvMarketPrice.setTextColor(LocalSp.getInstance(context).getEndColor());
                                tvMarketPercent.setTextColor(LocalSp.getInstance(context).getEndColor());
                            } else {
                                ivMarketPrice.setBackgroundResource(0);
                                tvMarketPrice.setTextColor(LocalSp.getInstance(context).getDefaultColor());
                                tvMarketPercent.setTextColor(LocalSp.getInstance(context).getDefaultColor());
                            }

                            tvMarketPrice.setText(String.valueOf(snapListResult.get_$55TBTC().getData().getLast().setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue()));
                            tvMarketPriceCNY.setText("¥ " + String.valueOf(snapListResult.get_$55TBTC().getData().getLast().multiply(new BigDecimal(6.5)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                            tvMarketPercent.setText(String.valueOf(percent) + "%");
                            tvMarket24Vol.setText(String.valueOf(snapListResult.get_$55TBTC().getData().getVolume().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                            tvMarket24Low.setText(String.valueOf(snapListResult.get_$55TBTC().getData().getLow().setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue()));
                            tvMarket24High.setText(String.valueOf(snapListResult.get_$55TBTC().getData().getHigh().setScale(8, BigDecimal.ROUND_HALF_UP).doubleValue()));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });

    }

    public CountDownTimer snapTimer = new CountDownTimer(24 * 60 * 60 * 1000, 1000) {
        @Override
        public void onTick(long l) {
            getSnapData();
        }

        @Override
        public void onFinish() {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (snapTimer != null) {
            snapTimer.cancel();
        }
    }
}
